package com.aspirecn.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.aspire.core.match.ua.object.Device;
import com.aspire.wap.core.http.RequestUtil;
import com.aspirecn.core.ShareCommon;
import com.aspirecn.core.commons.IPUtils;
import com.aspirecn.core.object.IP;

/**
 * 避免内部多次适配的加速器，请求时一次匹配，加载到request.attribute中
 * @author wangxinning
 *
 */
public class AccelerateFilter implements Filter{

	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		
		//1.ip
		String ip = IPUtils.getIP(httpServletRequest);
		httpServletRequest.setAttribute("sharecommon.ip", ip);
		
		//2.ipobject
		IP ipObject = IPUtils.getIPObject(ip);
		httpServletRequest.setAttribute("sharecommon.ipObject", ipObject);
		
		//3.ua
		String ua = RequestUtil.getUA(httpServletRequest);
		httpServletRequest.setAttribute("sharecommon.ua", StringUtils.trimToEmpty(ua));
		
		//4.uaobject
		Device device = ShareCommon.getInstance().getUACache()
				.matchUA(RequestUtil.getOriginalUserAgent(httpServletRequest));
		if( device != null )
		{
			httpServletRequest.setAttribute("sharecommon.uaObject", device);
		}
		
		//内部调用时如果attribute中已经包含，直接读取
		//想多了，直接在调用的时候加一个小缓存就可以，能满足一次请求的调用
		
		//返回
		chain.doFilter(request, response);		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
